from flask_restful import Resource, reqparse
from flask import jsonify
import random
from api.cache import cache
from config.setting import DevConfig
from api.sms import send_message

# 短信验证
class Phoneview(Resource):
    res = reqparse.RequestParser()
    res.add_argument('phone',type=str,location='form',help='手机')

    def post(self):
        par = self.res.parse_args()
        phone = par.get('phone')
        cade = self.get_cade(phone)

        # resp = send_message(phone,cade)

        return jsonify({
            # "resp":resp,
            "msg":"短信已发"
        })


    def get_cade(self,phone):
        # 生成验证码
        cade = str(random.randint(10000,99999))

        key = 'sms' + phone

        cache.set(key,cade,ex=int(DevConfig.Time)*60)

        print(cade)


        return cade


# 登录
class UserLoginView(Resource):
    res = reqparse.RequestParser()
    res.add_argument('phone', type=str, location='form', help='手机')
    res.add_argument('cade', type=str, location='form', help='验证码')
    def post(self):
        par = self.res.parse_args()
        phone = par.get('phone')
        cade = par.get('cade')

        par = self.get_cade(phone,cade)
        print(par)
        return jsonify(par)


    def get_cade(self,phone,cade):
        key = 'sms'+ phone
        ret = cache.get(key)
        if not ret:
            return jsonify({
                "msg":'验证码过期'
            })
        if ret.decode() != cade: return jsonify({"msg":'验证码不正确'})

        return jsonify({"msg":'验证码正确'})